package production.practice.utils;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用来做检验的,减少代码编写
 */
public class BinaryUtils {
    public static boolean isEmpty(Object v) {
        return isEmpty(v, true);
    }

    public static boolean isNotEmpty(Object v) {
        return !isEmpty(v, true);
    }

    public static boolean isEmpty(Object v, boolean trim) {
        if (v == null) {
            return true;
        } else if (v instanceof String) {
            String sv = (String)v;
            return trim ? sv.trim().length() == 0 : sv.length() == 0;
        } else if (v instanceof Collection) {
            Collection<?> c = (Collection)v;
            return c.size() == 0;
        } else if (v instanceof Map) {
            Map<?, ?> m = (Map)v;
            return m.size() == 0;
        } else if (isArray(v.getClass())) {
            return getArrayLength(v) == 0;
        } else {
            return false;
        }
    }

    public static boolean isArray(Class<?> c) {
        return c.isArray() || List.class.isAssignableFrom(c);
    }

    public static int getArrayLength(Object array) {
        return array == null ? 0 : (array instanceof List ? ((List)array).size() : Array.getLength(array));
    }

    public static void checkNull(Object value, String name) {
        if (value == null) {
            throw new IllegalArgumentException(" the '" + name + "' is null argument! ");
        }
    }

}
